package com.dmgameclient.activities;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import com.dmgameclient.R;
import com.dmgameclient.adapter.CommentsListViewAdapter;
import com.dmgameclient.beans.Comment;
import com.dmgameclient.common.HttpUtils;
import com.dmgameclient.common.JsonUtils;
import com.dmgameclient.common.UIHelper;
import com.dmgameclient.common.URLHelper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @name ContentFragment1
 * @Descripation <br>
 *               1、<br>
 *               2、<br>
 * @author 樊俊彬
 * @date 2014-9-19
 * @version 1.0
 */

public class CommentsActivity extends Activity {

	private static final String TAG = "CommentsActivity";

	// 头部
	private Button headerHome;
	private TextView headerTitle;
	private ProgressBar headerProgress;

	private ListView listView;
	private CommentsListViewAdapter adapter;
	private List<Comment> list = new ArrayList<Comment>();
	private Handler handler;

	// ListView列表底部视图
	private LinearLayout footerLayout;
	private TextView footerText;
	private ProgressBar footerProgress;

	// 页码
	private int page = 1;
	private String articleId;

	// 发表评论
	private EditText contentText;
	private Button pubButton;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// TODO Auto-generated method stub
		articleId = getIntent().getStringExtra("aid");
		setContentView(R.layout.comments_listview);
		initView();
		initFrame();
	}

	/**
	 * 加载界面组件
	 */
	private void initView() {

		// 头部
		headerHome = (Button) findViewById(R.id.headerHome);
		headerHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		headerTitle = (TextView) findViewById(R.id.headerTitle);
		headerTitle.setText("评论");

		// 正文
		listView = (ListView) findViewById(R.id.listView1);

		// ListView底部
		footerLayout = (LinearLayout) findViewById(R.id.footerLayout);
		footerText = (TextView) footerLayout
				.findViewById(R.id.listview_foot_more);
		footerProgress = (ProgressBar) footerLayout
				.findViewById(R.id.listview_foot_progress);

		// 发表
		contentText = (EditText) findViewById(R.id.contentText);
		pubButton = (Button) findViewById(R.id.pubButton);
		pubButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pubComment(contentText.getText().toString().trim());
			}
		});
	}

	/**
	 * 页面主要
	 */
	private void initFrame() {
		adapter = new CommentsListViewAdapter(this,
				R.layout.item_listview_comments, list, listView);
		listView.setAdapter(adapter);

		// 根据不同的操作刷新页面
		handler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				if (msg.obj != null) {
					switch (msg.arg1) {

					// 初始化加载
					case UIHelper.ACTION_TYPE_INIT:
						list.clear();
						list.addAll((List<Comment>) msg.obj);
						adapter.notifyDataSetChanged();
						footerLayout.setVisibility(View.GONE);
						break;

					// 滑动时不能清除数据
					case UIHelper.ACTION_TYPE_LOADMORE:
						list.addAll((List<Comment>) msg.obj);
						adapter.notifyDataSetChanged();
						footerLayout.setVisibility(View.GONE);
						break;

					// 发表评论
					case UIHelper.ACTION_TYPE_UPLOAD:
						if (((String) (msg.obj)).equals("1")) {
							contentText.setText("");
							Toast.makeText(CommentsActivity.this, "发表成功", 0)
									.show();
						} else {
							Toast.makeText(CommentsActivity.this,
									"网络响应异常，发表失败", 0).show();
						}
						progressDialog.dismiss();
					}
				}
			}
		};

		// 初始化不作任何操作时下载第1页
		loadData(1, UIHelper.ACTION_TYPE_INIT);

		// 滚动到底部时依次加载2、3、4...页数据
		listView.setOnScrollListener(new OnScrollListener() {
			boolean isBottom = false;

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO 捕获用户手势，是否飞滑到底部
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL
						&& isBottom) {
					footerLayout.setVisibility(View.VISIBLE);
					loadData(++page, UIHelper.ACTION_TYPE_LOADMORE);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount
						&& !isBottom) {
					isBottom = true;
				} else {
					isBottom = false;
				}
			}
		});
	}

	/**
	 * 下载评论数据
	 * 
	 * @param page
	 * @param actionType
	 */
	public void loadData(final int page, final int actionType) {
		footerLayout.setVisibility(View.VISIBLE);
		Executors.newSingleThreadExecutor().execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = Message.obtain();
				msg.arg1 = actionType;
				String jsonString = HttpUtils.downloadString(
						URLHelper.getCommentListUrl(articleId, page),
						URLHelper.BASE_URL);
				Log.i(TAG, ">>>com>>" + jsonString + ">>");
				msg.obj = JsonUtils.parseCommentList(jsonString);
				handler.sendMessage(msg);
			}
		});
	}

	/**
	 * 发表评论
	 * 
	 * @param content
	 */
	public void pubComment(String content) {
		startAnimation();
		Executors.newSingleThreadExecutor().execute(new Runnable() {
			@SuppressLint("UseValueOf")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = Message.obtain();

				try {
					Thread.sleep(1000);
					// HttpUtils.uploadString(content);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				msg.arg1 = UIHelper.ACTION_TYPE_UPLOAD;
				msg.obj = "0";
				handler.sendMessage(msg);
			}
		});
	}

	/**
	 * 开启动画
	 */
	private void startAnimation() {
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle("发表评论");
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
}
